package com.oktago.ibore;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.util.Linkify;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.ScrollView;
import android.widget.Scroller;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Iterator;

public class DetailActivity extends Activity {

    private ProgressDialog progressDialog;
    private final static int WAITING_PROGRESS_DIALOG_ID = 1;
    Long id = null;
    Handler myHandler;
    String content;
    private String jsonStringDetail;
    private JSONArray childrenTypes;
    int status = 0; //0=download node info; 1=download node details    
    SubTypesMenuAdapter adapter;
    IBoreApplication iBoreApplication;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail);
        iBoreApplication=(IBoreApplication)getApplication();
        Intent received = getIntent();
        Bundle argument = received.getExtras();
        if (argument != null && argument.containsKey("id")) {
            id = argument.getLong("id");
        }

        myHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                content = msg.obj.toString();
                if (content == null || content.equals("")) {
                    TextView contentError = (TextView) findViewById(R.id.ContentDetail);
                    contentError.setText(R.string.ErrorNotConnection);
                    dismissDialog(WAITING_PROGRESS_DIALOG_ID);
                    return;
                }
                if (status == 0) {
                    String jsonStringNode = msg.obj.toString();
                    JSONObject jo = null;
                    boolean details = false;
                    try {
                        jo = new JSONObject(jsonStringNode);
                        details = (jo.getBoolean("force_object"));
                        childrenTypes = jo.getJSONArray("subtypes");
                        GridView grid = (GridView) findViewById(R.id.ChildrenGridMenu);
                        if (childrenTypes.length()>0) {
                            adapter = new SubTypesMenuAdapter(DetailActivity.this, childrenTypes, new ArrayList<CustomFunction>(), id);
                            grid.setAdapter(adapter);
                            grid.setOnItemClickListener(adapter);
                        }
                        else  {
                            grid.setVisibility(View.GONE);
                        }
                    } catch (JSONException ex) {
                        Logger.getLogger(DetailActivity.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    if (details && id!=null) {
                        status = 1;
                        downloadDetail();
                        return;
                    }
                    else {
                        View detailView = findViewById(R.id.ContentDetail);
                        detailView.setVisibility(View.GONE);
                    }
                } else if (status == 1) {
                    jsonStringDetail = msg.obj.toString();
                    status=0;
                }
                //Visualizzazione
                visualizzaItem(jsonStringDetail, childrenTypes);
                dismissDialog(WAITING_PROGRESS_DIALOG_ID);
            }
        };

        startDownload();

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (iBoreApplication.loginActivated) {
            startDownload();
            iBoreApplication.loginActivated=false;
        }
    }

    private void visualizzaItem(String jsonString, JSONArray childrenTypes) {
        TextView detailTV = (TextView) findViewById(R.id.ContentDetail);
        detailTV.setScroller(new Scroller(DetailActivity.this));
        TextView titleTV = (TextView) findViewById(R.id.ItemDetailTitleTV);
        if (jsonString != null) {
            JSONObject j = null;
            try {
                j = new JSONObject(jsonString);
            } catch (JSONException ex) {
                Logger.getLogger(DetailActivity.class.getName()).log(Level.SEVERE, null, ex);
            }
            VisualizationUtility.visualizzaDettagli(j, detailTV, titleTV);
        }
    }

    void startDownload() {

        Thread downloader = new Thread() {

            @Override
            public void run() {
                try {
                    IBoreApplication application = (IBoreApplication) getApplication();
                    application.downloadNode(id, myResponseHandler);
                } catch (Exception e) {
                    Log.e("Pubblication Activity", "" + e);
                    showMessageOnOutput("");
                }
            }
        };

        // Visualizziamo una Dialog di attesa
        showDialog(WAITING_PROGRESS_DIALOG_ID);
        // Lo avviamo
        downloader.start();
    }

    private void downloadDetail() {

        Thread downloader = new Thread() {

            @Override
            public void run() {
                try {
                    IBoreApplication application = (IBoreApplication) getApplication();
                    application.downloadDetail(id, myResponseHandler);
                } catch (Exception e) {
                    Log.e("Pubblication Activity", "" + e);
                    showMessageOnOutput("");
                }
            }
        };

        // Visualizziamo una Dialog di attesa
        showDialog(WAITING_PROGRESS_DIALOG_ID);
        // Lo avviamo
        downloader.start();
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case WAITING_PROGRESS_DIALOG_ID:
                progressDialog = new ProgressDialog(this,
                        ProgressDialog.STYLE_SPINNER);
                progressDialog.setTitle("HTTP Connection");
                progressDialog.setMessage("Connecting...");
                progressDialog.setIndeterminate(true);
                return progressDialog;
            default:
                return null;
        }
    }

    public void showMessageOnOutput(String result) {
        Message msg = myHandler.obtainMessage();
        msg.obj = result;
        myHandler.sendMessage(msg);
    }
    private final ResponseHandler<String> myResponseHandler = new ResponseHandler<String>() {

        public String handleResponse(HttpResponse response)
                throws ClientProtocolException, IOException {
            // Estraiamo il risultato dalla risposta. Otteniamo quindi il content
            // da cui leggere le informazioni
            InputStream content = response.getEntity().getContent();
            byte[] buffer = new byte[1024];
            int numRead = 0;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while ((numRead = content.read(buffer)) != -1) {
                baos.write(buffer, 0, numRead);
            }
            // Chiudiamo lo stream
            content.close();
            // Otteniamo il risultato
            String result = new String(baos.toByteArray());

            showMessageOnOutput(result);

            return result;
        }
    };
}

class VisualizationUtility {

    /**
     * Classe di utilità che consente di trasformare oggetti JSON in Stringhe HTML per poter poi essere visualizzate su una TextView.
     * Si occupa inoltre di aggiungere al testo della stringa collegamenti per il riconoscimento di numeri di telefono, link web e e-mail.
     *
     *
     * @author Nunzio Cassavia
     * @info http://www.nemosoft.it
     * @version 1.0
     *
     *
     */
    private static String LOG_TAG = "ICAR";

    public static void visualizzaDettagli(JSONObject jso, TextView content, TextView TVTitle) {
        visualizzaDettagli(jso, content, TVTitle, null);
    }

    public static void visualizzaDettagli(JSONObject jso, TextView content, TextView TVTitle, TextView Location) {

        String DescTOT = "";
        String titleView = "";
        String onlyTitle = "";
        Log.i(LOG_TAG, "OBJECT LENGTH " + jso.length());
        try {

            JSONObject elements = jso.getJSONObject("ELEMENTS");

            //Diamo particolari visualizzazioni ai successivi 4 elementi

            if (elements.has("title")) {
                Log.i(LOG_TAG, "C e il titolo... ");

                JSONArray title = elements.getJSONArray("title");
                JSONObject current;
                Log.i(LOG_TAG, "Title Length " + title.length());
                for (int i = 0; i < title.length(); i++) {
                    current = title.getJSONObject(i);
                    if (current.has("VALUE")) {
                        Log.i(LOG_TAG, "Value ok " + current.getString("VALUE"));
                        onlyTitle += current.getString("VALUE");
                        titleView += "<font color=\"#0000a0\" size=5><strong><em>" + current.getString("VALUE") + "</em></strong></font>";

                    }
                }

            }
            if (elements.has("name")) {
                Log.i(LOG_TAG, "C e il titolo... ");

                JSONArray title = elements.getJSONArray("name");
                JSONObject current;
                Log.i(LOG_TAG, "Title Length " + title.length());
                for (int i = 0; i < title.length(); i++) {
                    current = title.getJSONObject(i);
                    if (current.has("VALUE")) {
                        Log.i(LOG_TAG, "Value ok " + current.getString("VALUE"));
                        onlyTitle += current.getString("VALUE");
                        titleView += "<font color=\"#0000a0\" size=10><strong><em>" + current.getString("VALUE") + "</em></strong></font>";

                    }
                }

            }

            if (elements.has("surname")) {
                Log.i(LOG_TAG, "C e il titolo... ");

                JSONArray title = elements.getJSONArray("surname");
                JSONObject current;
                Log.i(LOG_TAG, "Title Length " + title.length());
                for (int i = 0; i < title.length(); i++) {
                    current = title.getJSONObject(i);
                    if (current.has("VALUE")) {
                        Log.i(LOG_TAG, "Value ok " + current.getString("VALUE"));
                        onlyTitle += " " + current.getString("VALUE");
                        titleView += "<font color=\"#0000a0\" size=10><strong><em>  " + current.getString("VALUE") + "</em></strong></font>";

                    }
                }

            }

            titleView += "<br>";

            TVTitle.setText(Html.fromHtml(titleView));
            if (Location != null) {
                String loc = Location.getText().toString();
                String locationAppend = ""; //Stringa di max 20 caratteri da appendere nelle location derivante dal titolo
                for (int i = 0; i < 20; i++) {
                    locationAppend += "" + onlyTitle.charAt(i);
                    if (i >= onlyTitle.length() - 1) {
                        break;
                    }
                }

                if (onlyTitle.length() > 20) {
                    locationAppend += "...";
                }

                Location.setText(loc + " -> " + locationAppend);
            }
            // Elementi da mettere in testa subito dopo il titolo

            if (elements.has("abstract")) {
                Log.i(LOG_TAG, "C e il titolo... ");

                JSONArray abstractJ = elements.getJSONArray("abstract");
                JSONObject current;

                for (int i = 0; i < abstractJ.length(); i++) {
                    current = abstractJ.getJSONObject(i);
                    if (current.has("VALUE")) {
                        Log.i(LOG_TAG, "Value ok " + current.getString("VALUE"));
                        if (!current.getString("VALUE").equals("")) {
                            DescTOT += "</p><p><font color=\"#ff0000\"><strong><em>abstract</em></strong></font><br>" + current.getString("VALUE");
                        }
                    }
                }

            }

            if (elements.has("description")) {
                Log.i(LOG_TAG, "C e il titolo... ");

                JSONArray abstractJ = elements.getJSONArray("description");
                JSONObject current;

                for (int i = 0; i < abstractJ.length(); i++) {
                    current = abstractJ.getJSONObject(i);
                    if (current.has("VALUE")) {
                        Log.i(LOG_TAG, "Value ok " + current.getString("VALUE"));
                        if (!current.getString("VALUE").equals("")) {
                            DescTOT += "</p><p><font color=\"#ff0000\"><strong><em>description</em></strong></font><br>" + current.getString("VALUE");
                        }
                    }
                }

            }


            ArrayList<String> giaVisualizzati = new ArrayList<String>();
            giaVisualizzati.add("title");
            giaVisualizzati.add("name");
            giaVisualizzati.add("abstract");
            giaVisualizzati.add("description");
            giaVisualizzati.add("surname");
            String current = "";


            Iterator iter = elements.keys();


            while (iter.hasNext()) {

                current = (String) iter.next();
                if (elements.has(current)) {
                    Log.i(LOG_TAG, "C e l'elemento " + current);
                    try {
                        if (!giaVisualizzati.contains(current)) {

                            JSONArray currentElem = elements.getJSONArray(current);
                            JSONObject currentObj;

                            for (int j = 0; j < currentElem.length(); j++) {
                                currentObj = currentElem.getJSONObject(j);
                                if (currentObj.has("VALUE")) {
                                    Log.i(LOG_TAG, "Value ok " + currentObj.getString("VALUE"));
                                    if (!currentObj.getString("VALUE").equals("")) {

                                        DescTOT += "</p><p><font color=\"#ff0000\"><strong><em>" + current + "</em></strong></font><br>" + currentObj.getString("VALUE");
                                    }
                                }
                            }
                        }

                    } catch (JSONException e) {
                        //L'elemento non è un JSONArray ma un JSONObject... Non lo visualizziamo
                    }

                }
            }//while

            content.setText(Html.fromHtml(DescTOT));
            Linkify.addLinks(content, Linkify.EMAIL_ADDRESSES | Linkify.PHONE_NUMBERS | Linkify.WEB_URLS);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

